package edu.ynu.se.xiecheng.achitectureclass.common.service;

import edu.ynu.se.xiecheng.achitectureclass.common.dao.UserDAO;
import edu.ynu.se.xiecheng.achitectureclass.common.entity.User;
import edu.ynu.se.xiecheng.achitectureclass.common.utils.JwtUtil;
import edu.ynu.se.xiecheng.achitectureclass.common.utils.Md5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class UserService {

    @Autowired
    private UserDAO userDAO;

    public String login(String username, String password) {
        User user = userDAO.findByUserName(username);
        if (user != null && Md5Util.checkPassword(password, user.getPassword())) {
            Map<String, Object> claims = new HashMap<>();
            claims.put("userId", user.getId());
            claims.put("username", user.getUserName());
            return JwtUtil.genToken(claims);
        }
        return null;
    }

    public User register(String username, String password) {
        User existingUser = userDAO.findByUserName(username);
        if (existingUser != null) {
            return null; // 用户已存在
        }
        User user = new User();
        user.setUserName(username);
        user.setPassword(Md5Util.getMD5String(password));
        return userDAO.save(user);
    }
}
